package com.daichi.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.daichi.yygh.enums.PaymentTypeEnum;
import com.daichi.yygh.enums.RefundStatusEnum;
import com.daichi.yygh.model.order.OrderInfo;
import com.daichi.yygh.model.order.PaymentInfo;
import com.daichi.yygh.model.order.RefundInfo;
import com.daichi.yygh.order.mapper.OrderMapper;
import com.daichi.yygh.order.service.PaymentService;
import com.daichi.yygh.order.service.RefundInfoService;
import com.daichi.yygh.order.service.WeixinService;
import com.daichi.yygh.order.utils.HttpClient;
import com.daichi.yygh.order.utils.WxConstUtils;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl implements WeixinService {

    private final OrderMapper orderMapper;

    private final PaymentService paymentService;

    private final RedisTemplate redisTemplate;

    private final RefundInfoService refundInfoService;

    @Autowired
    public WeixinServiceImpl(OrderMapper orderMapper,
                             PaymentService paymentService,
                             RedisTemplate redisTemplate,
                             RefundInfoService refundInfoService) {
        this.orderMapper = orderMapper;
        this.paymentService = paymentService;
        this.redisTemplate = redisTemplate;
        this.refundInfoService = refundInfoService;
    }

    @Override
    public Map<String, Object> createNative(Long orderId) {
        try {

            Map<String, Object> redisMap = (Map<String, Object>) redisTemplate.opsForValue().get("orderId::" + orderId);
            if (redisMap != null) {
                return redisMap;
            }

            OrderInfo orderInfo = orderMapper.selectById(orderId);

            paymentService.savePayment(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

            // 设置参数调用微信生成二维码
            // 1、把参数转换xml格式，使用商户key进行加密
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", WxConstUtils.APPID);
            paramMap.put("mch_id", WxConstUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                    + (orderInfo.getReserveTime() == 0 ? "上午" : "下午") + "就诊" + orderInfo.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            //paramMap.put("total_fee", orderInfo.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");

            // 2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            // client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, WxConstUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            // 3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);

            // 4、封装结果集
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            // code_url二维码地址
            map.put("codeUrl", resultMap.get("code_url"));

            if (resultMap.get("result_code") != null) {
                redisTemplate.opsForValue().set("orderId::" + orderId, map, 120, TimeUnit.MINUTES);
            }

            return map;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            //1 根据orderId获取订单信息
            OrderInfo orderInfo = orderMapper.selectById(orderId);

            //2 封装提交参数
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", WxConstUtils.APPID);
            paramMap.put("mch_id", WxConstUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            //3 设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, WxConstUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //4 得到微信接口返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("支付状态resultMap:" + resultMap);

            //5 把接口数据返回
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean refund(Long orderId) {
        try {
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());

            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);

            // 判断是否已经退款
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }

            // 调用微信接口实现退款
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", WxConstUtils.APPID);       //公众账号ID
            paramMap.put("mch_id", WxConstUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id", paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no", paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no", "tk" + paymentInfo.getOutTradeNo()); //商户退款单号
//            paramMap.put("total_fee", paymentInfo.getTotalAmount().multiply(new BigDecimal("100")).longValue() + "");
//            paramMap.put("refund_fee", paymentInfo.getTotalAmount().multiply(new BigDecimal("100")).longValue() + "");
            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap, WxConstUtils.PARTNERKEY);

            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(WxConstUtils.PARTNER);
            client.post();

            // 返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
